import os import random from config.secret_key import secret_code from flask import Flask, make_response, request, render_template from cookie import set_cookie, cookie_check, get_cookie import pickle
defcookie_decode(data, key): data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())): return pickle.loads(base64.b64decode(msg)) returnNone
defwaf(data): blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen'] valid = False for word in blacklist: if word in data: valid = True break return valid
defcookie_check(key, secret=None): a = request.cookies.get(key) data = tob(request.cookies.get(key)) if data: if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(secret), msg, digestmod=hashlib.md5).digest())): res = base64.b64decode(msg) if waf(res): returnTrue else: returnFalse returnTrue else: returnFalse
defget_cookie(key, default=None, secret=None): value = request.cookies.get(key) if secret and value: dec = cookie_decode(value, secret) return dec[1] if dec and dec[0] == key else default return value or default
defcookie_is_encoded(data): returnbool(data.startswith(tob('!')) and tob('?') in data)
def_lscmp(a, b): returnnotsum(0if x == y else1for x, y inzip(a, b)) andlen(a) == len(b)
defset_cookie(name, value, secret=None, **options): if secret: value = touni(cookie_encode((name, value), secret)) resp = make_response("success") resp.set_cookie("user", value, max_age=3600) return resp elifnotisinstance(value, basestring): raise TypeError('Secret key missing for non-string Cookie.') iflen(value) > 4096: raise ValueError('Cookie value too long.')
defcookie_check(key, secret=None): a = request.cookies.get(key) data = tob(request.cookies.get(key)) if data: if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1)#cookie特征解密 if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(secret), msg, digestmod=hashlib.md5).digest())):#hashlib解密 res = base64.b64decode(msg)#b64解密 print(res) if waf(res):#waf检测 returnTrue else: returnFalse returnTrue else: returnFalse defget_cookie(key, default=None, secret=None): value = request.cookies.get(key) if secret and value: dec = cookie_decode(value, secret) return dec[1] if dec and dec[0] == key else default return value or default defcookie_is_encoded(data): returnbool(data.startswith(tob('!')) and tob('?') in data) defcookie_decode(data, key): data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1)#cookie特征解密 if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())):#hashlib解密 return pickle.loads(base64.b64decode(msg))#b64解密,pickle模块加载 returnNone
defwaf(data): blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen'] valid = False print(data) for word in blacklist: if word in data: valid = True print(word) return valid